import requests
import json
import time  # 导入time模块控制输出速度

def call_generate_sql(question: str):
    url = "http://localhost:3002/generate_sql"
    headers = {"Content-Type": "application/json"}
    data = {"question": question}

    try:
        with requests.post(url, headers=headers, json=data, stream=True) as response:
            response.raise_for_status()
            for line in response.iter_lines():
                if line:
                    decoded_line = line.decode('utf-8')
                    if decoded_line.startswith("data:"):
                        content = decoded_line[len("data:"):].strip()
                        if content == "[DONE]":
                            print("\n处理完成")  # 添加换行符保持格式
                            break
                        try:
                            json_data = json.loads(content)
                            sql_content = json_data.get('content', '')
                            # 逐字符输出并添加延迟
                            for char in sql_content:
                                print(char, end='', flush=True)
                                time.sleep(0.01)  # 控制输出速度（0.1秒间隔）
                        except json.JSONDecodeError:
                            print(f"\n非JSON内容: {content}")
    except requests.exceptions.RequestException as e:
        print(f"\n请求失败: {e}")

# 使用示例
call_generate_sql("统计一月份各卡口点的船舶通过数量，按照通过船舶数量降序排列，只显示通过量前10的卡口。")